package monster.com.cvh.adapter;

import android.app.Activity;
import android.content.DialogInterface;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import monster.com.cvh.R;
import monster.com.cvh.bean.HonorCertificateBean;
import monster.com.cvh.listener.OnHideKeyBoardListener;

/**
 * @author: 13580
 * @data: 2018/3/20
 * @function:荣誉证书adapter
 */

public class HonorCertificateAdapter extends BaseQuickAdapter<HonorCertificateBean.DataBean, BaseViewHolder> {
    private final Calendar mStartDate;
    private final Calendar mEndDate;
    private final Calendar mSelectedDate;
    private TimePickerView mPvGradutaionTime;
    private OnHideKeyBoardListener mListner;

    public HonorCertificateAdapter(@Nullable List<HonorCertificateBean.DataBean> data, OnHideKeyBoardListener listner) {
        super(R.layout.item_honor_certificate, data);
        mSelectedDate = Calendar.getInstance();//系统当前时间
        mStartDate = Calendar.getInstance();
        mStartDate.set(1970, 0, 1);
        mEndDate = Calendar.getInstance();
        mListner = listner;
    }

    @Override
    protected void convert(final BaseViewHolder helper, final HonorCertificateBean.DataBean item) {
        String prizeName = item.getScholarship_name();
        String prizeTime = item.getObtain_time();
        if (prizeName == null) {
            prizeName = "";
        }
        if (prizeTime == null) {
            prizeTime = "";
        }
        if (prizeTime.contains(".")) {
            String time = item.getObtain_time();
            prizeTime = time.substring(0, 4) + "年" + time.substring(5, 7) + "月";
        }
        helper.setText(R.id.tv_item_honor_certificate_title, mContext.getResources().getString(R.string.fragment_honot_certificate_title) + (helper.getLayoutPosition() + 1));
        EditText edtPrizeName = (EditText) helper.getView(R.id.edt_item_honor_certificate_prize_name);
        //防止notifyDataChange()导致值Editext重绘触发TextWatcher造成数据错乱
        if (edtPrizeName.getTag() instanceof TextWatcher) {
            edtPrizeName.removeTextChangedListener((TextWatcher) edtPrizeName.getTag());
        }
        edtPrizeName.setText(prizeName);
        TextWatcher edtPrizeNameWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mData.get(helper.getLayoutPosition()).setScholarship_name(s.toString().trim());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        edtPrizeName.addTextChangedListener(edtPrizeNameWatcher);
        edtPrizeName.setTag(edtPrizeNameWatcher);

        if (prizeTime.isEmpty()) {
            helper.setText(R.id.tv_item_honor_certificate_prize_time, mContext.getResources().getString(R.string.choose));
            helper.setTextColor(R.id.tv_item_honor_certificate_prize_time, mContext.getResources().getColor(R.color.tip_title));
        } else {
            helper.setText(R.id.tv_item_honor_certificate_prize_time, prizeTime);
            helper.setTextColor(R.id.tv_item_honor_certificate_prize_time, mContext.getResources().getColor(R.color.tv_title));
        }
        helper.getView(R.id.rel_item_honor_certificate_prize_time).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListner.onHideKeyBoard();
                if (item.getObtain_time() != null && item.getObtain_time().contains(".")) {
                    String time = item.getObtain_time();
                    mSelectedDate.set(Integer.parseInt(time.substring(0, 4)), Integer.parseInt(time.substring(5, 7)) - 1, 1);
                }
                initPrizeTime(helper);
            }
        });

        //如果只有一条item时，删除按钮不显示
        if (mData.size() == 1) {
            helper.setVisible(R.id.iv_item_honor_certificate_delete, false);
        } else {
            helper.setVisible(R.id.iv_item_honor_certificate_delete, true);
        }
        //当数据长度等3时，footer隐藏
        if (mData.size() == 3) {
            getFooterLayout().setVisibility(View.GONE);
        } else {
            getFooterLayout().setVisibility(View.VISIBLE);
        }
        //如果数据长度大于1，可以删除当前item
        helper.getView(R.id.iv_item_honor_certificate_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mData.size() > 1) {
                    //初始化删除弹窗
                    AlertDialog alertDialog = new AlertDialog.Builder(mContext)
                            .setMessage("是否删除荣誉证书"+(helper.getLayoutPosition()+1)+"?")
                            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .setPositiveButton(R.string.edt_info_delete, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    HonorCertificateAdapter.this.remove(helper.getAdapterPosition());
                                    notifyDataSetChanged();
                                    dialog.dismiss();
                                }
                            })
                            .create();
                    alertDialog.show();
                }
            }
        });
    }

    private void initPrizeTime(final BaseViewHolder helper) {
        mPvGradutaionTime = new TimePickerView.Builder(mContext, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                String time = getTime(date);
                if (time == null) {
                    time = "";
                }
                helper.setText(R.id.tv_item_honor_certificate_prize_time, time);
                helper.setTextColor(R.id.tv_item_honor_certificate_prize_time, mContext.getResources().getColor(R.color.tv_title));
                mData.get(helper.getLayoutPosition()).setObtain_time(time);
            }
        })
                .setDate(mSelectedDate)
                .setRangDate(mStartDate, mEndDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        TextView tvTitle = (TextView) v.findViewById(R.id.tv_pickerview_customer_launar_title);
                        final ImageView ivSubmit = (ImageView) v.findViewById(R.id.iv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvTitle.setText(mContext.getResources().getString(R.string.fragment_education_graduation_time));
                        ivSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvGradutaionTime.returnData();
                                mPvGradutaionTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvGradutaionTime.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, false, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(mContext.getResources().getColor(R.color.line_color))
                .setContentSize(20)
                .setLineSpacingMultiplier(2.0f)
                .setDecorView((ViewGroup) ((Activity) mContext).getWindow().getDecorView())
                .build();
        mPvGradutaionTime.show();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月");
        return format.format(date);
    }
}
